import {defineStore} from 'pinia'
import type {UserInfoDefine} from "../types/common"
import {getItem} from '../utils/storageUtil'
import {STORAGE_USER_TOKEN_KEY, STORAGE_USER_INFO_KEY} from '@/config/constants'
import pinia from "./index";


//命名一般为hook的方式(usexxx)
export const useUserStore = defineStore("user", {
    actions: {
        updateUserRoutersAttached(attached: boolean) {
            this.userRoutersAttached = attached;
        },
        storeUserInfo(userInfo: UserInfoDefine) {
            this.userInfo = userInfo;
        },
        storeToken(token: string) {
            this.token = token;
        },
        resetAll() {
            this.$reset();
        }
    },
    //存储数据的地方
    state() {
        return {
            userInfo: getItem(STORAGE_USER_INFO_KEY) ? JSON.parse(<string>getItem(STORAGE_USER_INFO_KEY)) : {
                id: '-1',
                userName: '',
                avatarPath: '',
                userRouters: [],
                backAuthorized: []
            } as unknown as UserInfoDefine,
            token: getItem(STORAGE_USER_TOKEN_KEY) || '',
            //是否已经添加动态路由
            userRoutersAttached: false,
        }
    }
})


export function useUserStoreExternal() {
    return useUserStore(pinia)
}